//
//  RecommendViewController.m
//  Wedding fantastic
//
//  Created by dllo on 15/6/29.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "RecommendViewController.h"
#import "GoodsCollectionViewCell.h"
#import "AFNetworking.h"
#import "RecommendModel.h"
#import "UIImageView+WebCache.h"
#import "searchViewController.h"
#import "GoodsDetailViewController.h"
#import "MBProgressHUD.h"
#import "SubjectMoreViewController.h"
#import "SellDetailViewController.h"
#import "CategoriesViewController.h"
#import "SellCollectionViewCell.h"
#import "SubjectCollectionViewCell.h"
#import "SubjectDetailVC.h"
#import "GuangGuangViewController.h"
#import "MoreSellViewController.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

@interface RecommendViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIAlertViewDelegate, UISearchBarDelegate>
//
@property (nonatomic, retain)UISearchBar *mySearch;
// 底部scrollerView
@property (nonatomic, retain)UIScrollView *backScrollView;
// 服务商家推荐collectionView
@property (nonatomic, retain)UICollectionView *sellCollectionView;
// 商品推荐collectionView
@property (nonatomic, retain)UICollectionView *goodsCollectionView;
// 主题婚品collectionView
@property (nonatomic, retain)UICollectionView *subjectCollectionView;
// 接收model(商品推荐)的数组
@property (nonatomic, retain)NSMutableArray *goodsArr;
// 接收服务商家推荐model的数组
@property (nonatomic, retain)NSMutableArray *sellArr;
// 接收主题婚品的图片数组
@property (nonatomic, retain)NSMutableArray *subjectPicArr;

//
@property (nonatomic, retain)MBProgressHUD *HUD;
@end

@implementation RecommendViewController
- (void)dealloc
{
    [_mySearch release];
    [_backScrollView release];
    [_sellCollectionView release];
    [_goodsCollectionView release];
    [_goodsArr release];
    [_sellArr release];
    [_subjectPicArr release];
    [_HUD release];
    [_sellCollectionView release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.goodsArr = [NSMutableArray array];
        self.sellArr = [NSMutableArray array];
        self.subjectPicArr = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    //搜索栏
    self.mySearch = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 5 * HEIGHT / 667, WIDTH, 34 * HEIGHT / 667)];
    self.mySearch.delegate = self;
    self.mySearch.showsCancelButton = NO;
    self.mySearch.barStyle = UIBarStyleBlackTranslucent;
    self.mySearch.placeholder = @"请输入套餐、商家、案例、商品";
    self.mySearch.keyboardType = UIKeyboardTypeNamePhonePad;
    [self.view addSubview:self.mySearch];
    [_mySearch release];
    self.navigationItem.titleView = self.mySearch;
    
    // 底部scroller
    self.backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 49)];
    self.backScrollView.backgroundColor = [UIColor colorWithRed:241 / 255.0 green:241 / 255.0 blue:240 / 255.0 alpha:1];
    [self.view addSubview:self.backScrollView];
    self.backScrollView.pagingEnabled = NO;
    // 设置滚动范围
    self.backScrollView.contentSize = CGSizeMake(0, HEIGHT * 3.62);
    [_backScrollView release];
    // 不显示滚动条
    self.backScrollView.showsVerticalScrollIndicator = FALSE;
    
    UIImageView *topImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 200 * HEIGHT / 667)];
    topImage.backgroundColor = [UIColor clearColor];
    topImage.image = [UIImage imageNamed:@"bg"];
    [self.backScrollView addSubview:topImage];
    [topImage release];

    // 服务商家推荐标题 "更多" Button
    UIButton *sellButton = [UIButton buttonWithType:UIButtonTypeSystem];
    sellButton.frame = CGRectMake(0, 200 * HEIGHT / 667, WIDTH, 50 * HEIGHT / 667);
    sellButton.backgroundColor = [UIColor whiteColor];
    [sellButton setTitle:@"服务商家推荐                                           更多 >>" forState:UIControlStateNormal];
    sellButton.titleLabel.font = [UIFont systemFontOfSize:14.5];
    [sellButton setTintColor:[UIColor blackColor]];
    [self.backScrollView addSubview:sellButton];
    [sellButton addTarget:self action:@selector(sellButtonClick:) forControlEvents:UIControlEventTouchUpInside];

    // 服务商家推荐ScrollView
    UIScrollView *recommentScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 250 * HEIGHT / 667, WIDTH, 130 * HEIGHT / 667)];
    recommentScrollView.backgroundColor = [UIColor whiteColor];
    // 滚动范围
    recommentScrollView.contentSize = CGSizeMake(WIDTH * 1.9, 0);
    // 按页滚动
    recommentScrollView.pagingEnabled = NO;
    [self.backScrollView addSubview:recommentScrollView];
    [recommentScrollView release];
    recommentScrollView.showsHorizontalScrollIndicator = FALSE;

    // 服务商家collectionView
    UICollectionViewFlowLayout *sellLayout = [[UICollectionViewFlowLayout alloc] init];
    sellLayout.itemSize = CGSizeMake(130 * WIDTH / 375, 120 * HEIGHT / 667);
    sellLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    sellLayout.sectionInset = UIEdgeInsetsMake(10 * HEIGHT / 667, 10 * WIDTH / 375, 0, 0);
    
    self.sellCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 2.22, 130 * HEIGHT /667) collectionViewLayout:sellLayout];
    self.sellCollectionView.dataSource = self;
    self.sellCollectionView.delegate = self;
    self.sellCollectionView.backgroundColor = [UIColor whiteColor];
    [recommentScrollView addSubview:self.sellCollectionView];
    [_sellCollectionView release];
    
    [self.sellCollectionView registerClass:[SellCollectionViewCell class] forCellWithReuseIdentifier:@"sellReuse"];

    
    // 主题婚品 "更多" Button
    UIButton *subjectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    subjectButton.frame = CGRectMake(0, 390 * HEIGHT / 667, WIDTH, 50 * HEIGHT / 667);
    [subjectButton setTitle:@" 主题婚品                                                 更多 >>" forState:UIControlStateNormal];
    subjectButton.backgroundColor = [UIColor whiteColor];
    subjectButton.titleLabel.font = [UIFont systemFontOfSize:14.5];
    [subjectButton setTintColor:[UIColor blackColor]];
    [self.backScrollView addSubview:subjectButton];
    [subjectButton addTarget:self action:@selector(subjectButtonClick:) forControlEvents:UIControlEventTouchUpInside];

    // 主题婚品scrollView
    UIScrollView *subjectScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 440 * HEIGHT / 667, WIDTH, 150 * HEIGHT / 667)];
    subjectScrollView.backgroundColor = [UIColor whiteColor];
    // 滚动范围
    subjectScrollView.contentSize = CGSizeMake(WIDTH * 5.25, 0);
    subjectScrollView.pagingEnabled = NO;
    subjectScrollView.tag = 1001;
    [self.backScrollView addSubview:subjectScrollView];
    [subjectScrollView release];
    // 不显示滚动条
    subjectScrollView.showsHorizontalScrollIndicator = FALSE;
    
    // 主题婚品collectionView
    UICollectionViewFlowLayout *subjectLayout = [[UICollectionViewFlowLayout alloc] init];
    subjectLayout.itemSize = CGSizeMake(120 * WIDTH / 375, 140 * HEIGHT / 667);
    subjectLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    subjectLayout.sectionInset = UIEdgeInsetsMake(0, 10 * WIDTH / 375, 0, 0);
    
    self.subjectCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 5.5, 150 * HEIGHT / 667) collectionViewLayout:subjectLayout];
    self.subjectCollectionView.delegate = self;
    self.subjectCollectionView.dataSource = self;
    self.subjectCollectionView.backgroundColor = [UIColor whiteColor];
    [subjectScrollView addSubview:self.subjectCollectionView];
    [_subjectCollectionView release];
    // 注册
    [self.subjectCollectionView registerClass:[SubjectCollectionViewCell class] forCellWithReuseIdentifier:@"subjectReuse"];
    
    // 商品推荐 "更多" Button
    UIButton *goodsButton = [UIButton buttonWithType:UIButtonTypeSystem];
    goodsButton.frame = CGRectMake(0, 600 * HEIGHT / 667, WIDTH , 50 * HEIGHT / 667);
    goodsButton.backgroundColor = [UIColor whiteColor];
    [goodsButton setTitle:@" 商品推荐                                                 更多 >>" forState:UIControlStateNormal];
    goodsButton.titleLabel.font = [UIFont systemFontOfSize:14.5];
    [goodsButton setTintColor:[UIColor blackColor]];
    [self.backScrollView addSubview:goodsButton];
    [goodsButton addTarget:self action:@selector(goodsClick:) forControlEvents:UIControlEventTouchUpInside];
    
    // 最新商品
    UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(0, 660 * HEIGHT /677, WIDTH, 30 * HEIGHT / 677)];
    newView.backgroundColor = [UIColor whiteColor];
    [self.backScrollView addSubview:newView];
    [newView release];
    
    // 最新商品label
    UILabel *newGoodsLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 125 * WIDTH / 375, 30 * HEIGHT / 677)];
    newGoodsLable.text = @"  最热商品Top 20";
    newGoodsLable.font = [UIFont systemFontOfSize:13];
    [newView addSubview:newGoodsLable];
    [newGoodsLable release];
    
    //
    // 苹果官方提供的一种瀑布流效果
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 每一个item的大小
    flowLayout.itemSize = CGSizeMake(150 * WIDTH / 375, 160 * HEIGHT / 667);
    flowLayout.sectionInset = UIEdgeInsetsMake(5 * WIDTH / 375, 25 * HEIGHT / 667, 5 * WIDTH / 375, 25 * HEIGHT / 667);

    
    self.goodsCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 680 * HEIGHT / 667, WIDTH, HEIGHT * 2.65) collectionViewLayout:flowLayout];
    self.goodsCollectionView.backgroundColor = [UIColor whiteColor];
    // collectionView和tableView很相似,使用前需要先签订两个协议,一个dataSource,一个delegate
    self.goodsCollectionView.delegate = self;
    self.goodsCollectionView.dataSource = self;
    [self.backScrollView addSubview:self.goodsCollectionView];
    [_goodsCollectionView release];
    
    // 注册
    // 第一个参数:需要指定注册类型
    // 第二个参数:重用的标志
    [self.goodsCollectionView registerClass:[GoodsCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    
    // 回到顶部button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(300 * WIDTH / 375, 450 * HEIGHT / 667, 35 * WIDTH / 375, 38 * HEIGHT / 667);
    [button setBackgroundImage:[UIImage imageNamed:@"backTop"] forState:UIControlStateNormal];
    button.alpha = 0.6;
    [self.view addSubview:button];
    [button addTarget:self action:@selector(backTop:) forControlEvents:UIControlEventTouchUpInside];
    
    // 提示label
    UILabel *tishiLable = [[UILabel alloc] initWithFrame:CGRectMake(90 * WIDTH / 375, HEIGHT * 3.62, 250 * WIDTH / 375, 40 * HEIGHT / 677)];
    tishiLable.textColor = [UIColor grayColor];
    tishiLable.font = [UIFont systemFontOfSize:14];
    tishiLable.text = @"---查看更多商品,请点击更多---";
    [self.backScrollView addSubview:tishiLable];
    [tishiLable release];
    
    [self createSellData];
    [self createGoodsData];
    [self createSubjectData];

}


// 下拉
- (void)headerRereshing
{
    [self.goodsCollectionView reloadData];
    // 刷新结束
    [self.backScrollView headerEndRefreshing];
}

// 回到顶部
- (void)backTop:(UIButton *)button
{
    [self.backScrollView setContentOffset:CGPointZero animated:YES];
}

// 商家推荐更多按钮
- (void)sellButtonClick:(UIButton *)button
{
    MoreSellViewController *moreVC = [[MoreSellViewController alloc] init];
    [self.navigationController pushViewController:moreVC animated:YES];
    [moreVC release];
}

// 主题婚品更多按钮点击方法
- (void)subjectButtonClick:(UIButton *)button
{
    SubjectMoreViewController *subjectVC = [[SubjectMoreViewController alloc] init];
    [self.navigationController pushViewController:subjectVC animated:YES];
    [subjectVC release];
}
// 主题婚品图片点击方法
- (void)goodsClick:(UIButton *)button
{
    GuangGuangViewController *guangVC = [[GuangGuangViewController alloc] init];
    [self.navigationController pushViewController:guangVC animated:YES];
    [guangVC release];
}

//searchBar触发
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    searchViewController *search = [[searchViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
    [search release];
    return YES;
}


// collectionView 的方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if ([collectionView isEqual:self.goodsCollectionView]) {
        return self.goodsArr.count;
    } else if ([collectionView isEqual:self.subjectCollectionView]) {
        return self.subjectPicArr.count;
    } else {
        return self.sellArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([collectionView isEqual:self.goodsCollectionView]) {
        RecommendModel *model = self.goodsArr[indexPath.row];
        GoodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
        // 使用了注册,不需要判断是否为空
        cell.contentView.backgroundColor = [UIColor whiteColor];
        cell.priceLabel.text = [NSString stringWithFormat:@"￥%@", [model.price stringValue]];
        cell.recommendLabel.text = [model.like_count stringValue];
        [cell.topImageView sd_setImageWithURL:[NSURL URLWithString:model.photo_path]];
        
        //3D效果
        cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
        [UIView animateWithDuration:0.5 animations:^{
            
            cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
        }];

        return cell;
    } else if ([collectionView isEqual:self.subjectCollectionView]) {
        RecommendModel *model = self.subjectPicArr[indexPath.row];
        SubjectCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"subjectReuse" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:model.cover_path]];
        
        return cell;
    } else {
        RecommendModel *model = self.sellArr[indexPath.row];
        SellCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"sellReuse" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        [cell.topImageView sd_setImageWithURL:[NSURL URLWithString:model.logo_path]];
        cell.nameLabel.text = model.name;
        return cell;
    }
}

// collectionView点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([collectionView isEqual:self.goodsCollectionView]) {
        GoodsDetailViewController *goodsDetailVC = [[GoodsDetailViewController alloc] init];
        goodsDetailVC.sendModel = self.goodsArr[indexPath.row];
        [self.navigationController pushViewController:goodsDetailVC animated:YES];
        [goodsDetailVC release];
    } else if ([collectionView isEqual:self.subjectCollectionView]) {
        SubjectDetailVC *subjectVC = [[SubjectDetailVC alloc] init];
        subjectVC.sendModel = self.subjectPicArr[indexPath.row];
        [self.navigationController pushViewController:subjectVC animated:YES];
        [subjectVC release];
    } else {
        SellDetailViewController *selldetailVC = [[SellDetailViewController alloc] init];
        selldetailVC.sendModel = self.sellArr[indexPath.row];
        [self.navigationController pushViewController:selldetailVC animated:YES];
        [selldetailVC release];
    }
}

// 解析商品推荐数据
- (void)createGoodsData
{
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.HUD setDimBackground:YES];
    self.HUD.labelText = @"努力加载中...";
    [self.HUD show:YES];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://www.hunliji.com/v1/api/app/products.json?per_page=20&page=1" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        NSArray *productsArr = dic[@"products"];
        for (NSDictionary *tempDic in productsArr) {
            RecommendModel *model = [[RecommendModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            [self.goodsArr addObject:model];
            [model release];
        }
        [self.HUD hide:YES];
        [self.goodsCollectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您的网络有问题" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alert show];
        [alert release];
    }];
}

// 解析商家推荐数据
- (void)createSellData
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://www.hunliji.com/v1/api/app/merchants/fine.json?city=0&page=1&per_page=10" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSDictionary *dic = responseObject;
        NSArray *merchantsArr = dic[@"merchants"];
        for (NSDictionary *tempDic in merchantsArr) {
            RecommendModel *model = [[RecommendModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            [self.sellArr addObject:model];
            [model release];
        }
        [self.sellCollectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

// 解析主题婚品图片
- (void)createSubjectData
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://www.hunliji.com/v1/api/app/newsubjects.json?page=1&per_page=15" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        NSArray *subjectsArr = dic[@"subjects"];
        for (NSDictionary *tempDic in subjectsArr) {
            RecommendModel *model = [[RecommendModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            [self.subjectPicArr addObject:model];
            [model release];
        }
        [self.subjectCollectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
